package com.strange.mdl.module.mdl.controller.app.user;

import com.alibaba.cloud.ai.dashscope.image.DashScopeImageModel;
import com.alibaba.cloud.ai.dashscope.image.DashScopeImageOptions;
import com.strange.mdl.framework.common.pojo.CommonResult;
import com.strange.mdl.framework.common.util.object.BeanUtils;
import com.strange.mdl.module.mdl.controller.admin.user.vo.MdlUserRespVO;
import com.strange.mdl.module.mdl.dal.dataobject.user.MdlUserDO;
import com.strange.mdl.module.mdl.service.user.MdlUserService;
import com.strange.mdl.module.mdl.utils.OssUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URI;
import java.net.URL;

import static com.strange.mdl.framework.common.pojo.CommonResult.success;
import static com.strange.mdl.module.mdl.enums.ErrorCodeConstants.IMAGE_NOT;

@Tag(name = "app-用户会员接口")
@RestController
@RequestMapping("/mdl/user")
@Validated
@Slf4j
public class AppUserController {
    @Resource
    private MdlUserService userService;

    @GetMapping("/get")
    @Operation(summary = "获得用户")
    @Parameter(name = "id", description = "编号", required = true, example = "2")
    public CommonResult<MdlUserRespVO> getUser(@RequestParam("id") Long id) {
        MdlUserDO user = userService.getUser(id);
        return success(BeanUtils.toBean(user, MdlUserRespVO.class));
    }

    @Autowired
    private DashScopeImageModel imageModel;

    @Autowired
    private OssUtil ossUtil;

    @GetMapping("/RemoveBackground")
    @PermitAll
    public void RemoveBackground() throws IOException {
        // 读取原始图片
//        File input = new File("https://scripture.oss-cn-shenzhen.aliyuncs.com/face/20250628/0a619d01e0c64663930b77fecf7c567c.png");
//        BufferedImage image = ImageIO.read(input);
        URL url = new URL("https://scripture.oss-cn-shenzhen.aliyuncs.com/face/20250628/0a619d01e0c64663930b77fecf7c567c.png");
        BufferedImage image = ImageIO.read(url);

        int width = image.getWidth();
        int height = image.getHeight();

        // 定义要移除的颜色（白色）
        int removeColor = 0xFFFFFF; // 白色 (RGB: 255,255,255)

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int rgb = image.getRGB(x, y);

                // 提取 RGB 颜色值（忽略 alpha）
                int red = (rgb >> 16) & 0xFF;
                int green = (rgb >> 8) & 0xFF;
                int blue = rgb & 0xFF;

                int currentColor = (red << 16) | (green << 8) | blue;

                if (currentColor == removeColor) {
                    // 设置为透明 (alpha = 0)
                    image.setRGB(x, y, 0x00FFFFFF); // Alpha = 0
                }
            }
        }

        // 保存处理后的图片（PNG 格式支持透明）
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos); // 将BufferedImage写入ByteArrayOutputStream
        byte[] imageData = baos.toByteArray();
        // 将byte数组转换为InputStream
        InputStream in = new ByteArrayInputStream(imageData);
        String faceUrl = ossUtil.upload(in, "output.png", "face");
        System.out.println("处理完成，输出文件: " + faceUrl);
    }

    @GetMapping("/generateface")
    @PermitAll
    public CommonResult<String> getImage(@RequestParam(value = "msg",defaultValue = "女孩")
                                         String msg) {
//        String promptTemplate = "一个3D卡通风格的%s，黑色短发，发型自然蓬松，大而圆的眼睛，眼神明亮有神，面带温暖的笑容，人物穿着一件简单的黑色T恤和黑色裤子站立照，衣服剪裁合身，显得干净利落。背景无色的png格式图片，突出人物主体。整体风格可爱、现代，适合用于儿童或青少年相关的应用。";
        String promptTemplate = "一个3D卡通风格的%s，黑色短发，发型自然蓬松，大而圆的眼睛，眼神明亮有神，面带温暖的笑容，人物穿着一件简单的黑色T恤和黑色裤子站立照，衣服剪裁合身，显得干净利落。背景是透明的png格式图片，突出人物主体。整体风格可爱、现代，适合用于儿童或青少年相关的应用。";

        String msgs = String.format(promptTemplate, msg);
        ImageResponse imageResponse = imageModel.call(
                new ImagePrompt(
                        msgs,
                        DashScopeImageOptions.builder()
                                .withModel("wanx2.1-t2i-plus")
                                .withN(1)
                                .withHeight(512)
                                .withWidth(512)
                                .build()
                )
        );
        //获取生成图像的地址
        String imageUrl = imageResponse.getResult().getOutput().getUrl();
        // 上传oss存储
        try {
            URL url = URI.create(imageUrl).toURL();
            InputStream in = url.openStream();
            String faceUrl = ossUtil.upload(in, url.getPath(), "face");
            log.info("faceUrl:{}", faceUrl);
            return CommonResult.success(faceUrl);
        }catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.error(IMAGE_NOT);
        }
    }

}
